#pragma once
#include "log.hpp"
#include "ThreadPool.hpp"
#include "Text.hpp"
#include <string>
#include <cstring>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cerrno>
#include <cstdlib>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <functional>
#include <wait.h>
#include <cstdlib>
#include <pthread.h>

namespace Server
{
    void serviceIO(int sock)
    {
        char buffer[1024];
        while (true)
        {
            ssize_t n = read(sock, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << "recv message: " << buffer << std::endl;

                std::string outbuffer = buffer;
                outbuffer += "server[echo]";

                write(sock, outbuffer.c_str(), outbuffer.size());
            }
            else if (n == 0)
            {
                // 代表client退出
                logMessage(NORMAL, "client quit,me too");
                break;
            }
        }
    }

    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR,
        LISTEN_ERR,
        OPEN_ERR
    };

    static const uint16_t gport = 8080;
    static const int gbacklog = 5;
    class tcpServer;

    class ThreadData
    {
    public:
        ThreadData(tcpServer *self, int sock)
            : _self(self), _sock(sock)
        {
        }

    public:
        tcpServer *_self;
        int _sock;
    };

    class tcpServer
    {
    public:
        tcpServer(const uint16_t &port = gport)
            : _listensock(-1), _port(port)
        {
        }

        void initServer()
        {
            // 1.创建
            _listensock = socket(AF_INET, SOCK_STREAM, 0);
            if (_listensock < 0)
            {
                logMessage(FATAL, "create listensock error");
                exit(SOCKET_ERR);
            }
            logMessage(NORMAL, "create listensock success");

            // 2.bind
            struct sockaddr_in local;
            memset(&local, 0, sizeof local);
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = INADDR_ANY;
            if (bind(_listensock, (struct sockaddr *)&local, sizeof local) < 0)
            {
                logMessage(FATAL, "bind error");
                exit(BIND_ERR);
            }
            logMessage(NORMAL, "bind listensock success");

            // 3.设置socket，为监听状态
            if (listen(_listensock, gbacklog))
            {
                logMessage(FATAL, "listen error");
                exit(LISTEN_ERR);
            }
            logMessage(NORMAL, "listen listensock success");
        }

        void start()
        {
            // signal(SIGCHLD, SIG_IGN);
            // 线程池初始化
            ThreadPool<Task>::getInstance()->run();
            for (;;)
            {
                // 1.sever获取新链接
                struct sockaddr_in peer;
                socklen_t len = sizeof peer;
                int sock = accept(_listensock, (struct sockaddr *)&peer, &len);
                if (sock < 0)
                {
                    logMessage(ERROR, "accept error, next"); // accept失败不影响整体的代码，继续访问即可
                    continue;
                }
                logMessage(NORMAL, "accept a new link success");
                std::cout << "sock: " << sock << std::endl;

                // 1.单一执行流
                // sock是面向字节流的，后续全部都是文件操作
                // serviceIO(sock);
                // close(sock); //不释放会出现文件描述符泄漏

                // 2.多进程
                // pid_t id = fork();
                // if (id == 0)
                // {
                //     // child
                //     close(_listensock);
                //     // if (fork() > 0)
                //     //     exit;

                //     // 孙子进程变为孤儿进程
                //     serviceIO(sock);
                //     close(sock);
                //     exit(0);
                // }
                // close(sock);
                // // father
                // pid_t ret = waitpid(id, nullptr, 0); //子进程进去直接死亡回收，不需要管理
                // if (ret > 0)
                //     std::cout << "wait success: " << ret << std::endl;

                // 3.多线程
                // pthread_t tid;
                // ThreadData *td = new ThreadData(this, sock);
                // pthread_create(&tid, nullptr, threadRoutine, td);

                // pthread_join(tid, nullptr);

                // 4.线程池
                ThreadPool<Task>::getInstance()->push(Task(sock, serviceIO));
            }
        }

        // static void *threadRoutine(void *args)
        // {
        //     pthread_detach(pthread_self());
        //     ThreadData *td = static_cast<ThreadData *>(args);

        //     td->_self->serviceIO(td->_sock);
        //     delete td;
        //     close(td->_sock);
        //     return nullptr;
        // }

        ~tcpServer()
        {
        }

    private:
        uint16_t _port;
        int _listensock; // 不是用来通信的，而是用于监听链接的
    };
}